package com.liuzhilin.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.liuzhilin.domain.Article;
import com.liuzhilin.service.ManagerService;
import com.liuzhilin.util.Response;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@WebServlet("/managerArticleNotPass")
public class ManagerArticleNotPass extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应类型为 JSON
        Response.setCorsHeaders(response);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();

        // 获取请求中的 JSON 数据
        StringBuilder sb = new StringBuilder();
        String line = null;
        try (BufferedReader reader = request.getReader()) {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }
        String json = sb.toString();

        // 将 JSON 数据转换为 Java 对象
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, String> data =objectMapper.readValue(json, Map.class);
        String writer = data.get("writer");
        String title = data.get("title");
        String category = data.get("category");
        String adminName = data.get("adminName");


        // 调用业务逻辑层，更新文章状态为不通过
        boolean result = ManagerService.notPassArticle(writer,title,category); // 假设 2 表示不通过

        // 返回结果
        if (result) {
            if(adminName!=null){
                ManagerService.recordOperationLog(adminName, "判定用户"+writer+"发布在"+category+"标题为"+title+"的文章不通过",writer);
            }
            out.write("{\"message\": \"审核不通过成功！\"}");
            response.setStatus(HttpServletResponse.SC_OK); // 设置状态码为 200
        } else {
            out.write("{\"message\": \"审核不通过失败！\"}");
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); // 设置状态码为 500
        }
    }

    @Override
    public void doOptions(HttpServletRequest request, HttpServletResponse response) {
        // 设置 CORS 头部
        Response.setCorsHeaders(response);
        response.setStatus(HttpServletResponse.SC_OK);
    }
}
